package com.example.entity;

import com.example.util.StringUtil;
import com.example.util.UuidUtils;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;

import java.io.Serializable;

public class UUIDGenerator implements IdentifierGenerator {

    @Override
    public Serializable generate(SharedSessionContractImplementor sessionImplementor, Object object) throws HibernateException {

        if (null == object) {
            throw new IllegalArgumentException("保存对象不能为空");
        }
        if (!(object instanceof BaseEntity)) {
            throw new IllegalArgumentException(object.getClass() + "必须继承 BaseEntity");
        }

        if (StringUtil.isBlank((((BaseEntity) object).getId()))) {
            return UuidUtils.base58Uuid();
        } else {
            return ((BaseEntity) object).getId();
        }
    }
}
